package com.yb.bussiness.goods;

import java.util.List;

import com.yb.base.dao.BaseDao;
import com.yb.base.dao.IBaseDao;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.goods.TpingGou;

public class TpingGouServiceImpl implements TpingGouService {
	private IBaseDao<TpingGou, Long> dao;
	private IBaseDao<TgBrand, Long> brandDao;

	public TpingGouServiceImpl() {
		dao = new BaseDao<TpingGou, Long>(TpingGou.class);
		brandDao = new BaseDao<TgBrand, Long>(TgBrand.class);
	}

	public boolean addOrUpdate(TpingGou tp) {
		delete(tp.getBrandId(), tp.getCategoryId(), tp.getTypeId());
		dao.saveOrUpdate(tp);
		return true;
	}

	public void deleteById(Long id) {
		dao.deleteById(id);
	}

    public void delete(Long brandId, Long categoryId, Long typeId) {
        String sql = "delete from t_pinggou  ";
        if (null != typeId&&typeId!=0) {
            sql += "where brandId=" + brandId + " and typeId = " + typeId
                    + " and categoryId = " + categoryId;
        } else {
            sql += "where brandId=" + brandId + " and categoryId = "
                    + categoryId;
        }
        dao.delete(sql);
    }

	public void modifyWeights(Long brandId, Long categoryId, Long typeId,
			int weights) {
		String sql = "update t_pinggou set weights = ? where brandId = ?";
		sql += " and categoryId = ?";
		if (typeId > 0l) {
			sql += " and typeId = ?";
			dao.update(sql,
					new Object[] { weights, brandId, categoryId, typeId });
		} else {
			dao.update(sql, new Object[] { weights, brandId, categoryId });
		}
	}

	public List<TgBrand> findPingouByCategoryId(Long categoryId) {
		String sql = "select tbg.id,tbg.name,tbg.imgsrc,tpi.weights auding from t_g_brand tbg,t_pingou_index tpi,t_pinggou tpg"
				+ " where tbg.id = tpg.brandId and tpg.id = tpi.pingouId and tpi.categoryId = ? order by tpi.weights desc";
		return brandDao.findList(sql, new Object[] { categoryId });
	}

	public boolean checkDel(String id, Long categoryId, Long typeId) {
		if (null == id || "".equals(id))
			return true;
		boolean flag = true;
		String[] idAry = id.split("_");
		for (int i = 0; i < idAry.length; i++) {
			if (flag) {
				String sql = "select count(*) from t_pingou_index tpi where exists (select 1 from t_pinggou tpg where tpg.id = tpi.pingouId and tpg.categoryId = ? and tpg.brandId = ?) ";
				if (bulidResult(sql, new Object[] { categoryId, idAry[i] }) > 0)
					flag = false;
			}else{
				break;
			}
		}
		return flag;
	}

	private int bulidResult(String sql, Object[] conditionAry) {
		int count = 0;
		List<Object[]> list = dao.findObjectArryList(sql, conditionAry);
		Object[] objAry = list.get(0);
		count = new Integer(objAry[0].toString());
		return count;
	}
}
